package com.thread;

/**
 * @author :admin
 * @description: 线程状态测试
 * isAlive() 测试线程是否处于活动状态。如果线程已经启动且尚未终止，则为活动状态。
 * 该方法在某些情况状态是不明确的，不如下面的例子
 * 原因：如果将线程对象以构造方式传给Thread对象，进行start()启动时会存在差异，造成差异的原因
 * 就是this 与 Thread.currentThread() 的区别，ID也不一样
 * @create date: 2019/4/3 10:53
 */
public class ThreadState extends Thread {

    private String shareName;

    public ThreadState(String shareName) {
        this.shareName = shareName;
    }

    @Override
    public void run() {

//        实现同步，解决shareName引起的线程安全
        Thread currentThread = Thread.currentThread();
        System.out.println("this threadName" + this.getName() + " :" + this.isAlive() + " id :"
                + this.getId() + "\n current thread :" + currentThread.getName() + " :" + currentThread.isAlive()+" id :"+currentThread.getId());
    }

    public static void main(String[] args) throws InterruptedException {
        ThreadState threadShare = new ThreadState("s1");
        Thread thread = new Thread(threadShare, "A1");
        System.out.println("state1 =" + thread.isAlive() + " id :" + thread.getId());
        thread.start();
        Thread.sleep(1900);
        System.out.println("state2 =" + thread.isAlive() + " id :" + thread.getId());
    }
}
